<?php
namespace app\admin\model;
use think\Model;

class Admin extends Model
{
    
    public function addadmin($data){
      if(empty($data)|| !is_array($data)){
          return false;
      }
      if($data['password'] !=''){
        $data['password']=md5( $data['password']);
      }

      $datas['name']=$data['name'];
      $datas['password']=$data['password'];
      if($this->save($datas)){
          $groupAccess=array();
          $groupAccess['uid']=$this->id;
          $groupAccess['group_id']=$data['group_id'];
          db('auth_group_access')->insert($groupAccess);
         return true;
      }else{
        return false;
      }
    }
    
    public function getadmin(){
      //分页查询
      return $this::paginate(3);
    }

    public function edit($data,$admins){
       if(!$data['name']){
                return 2;//$this->error('管理员名称不得为空！');
            }

            if(!isset($data['password'])){
                $data['password']=$admins['password'];
            }else{
                $data['password']=md5($data['password']);
            }
          //dump($data);die;
          $datas['name']=$data['name'];
          $datas['password']=$data['password'];
          

          $authgroup=array();
          $authgroup['group_id']=$data['group_id'];
          //dump($authgroup);die;
         $tat=db('auth_group_access')->where('uid',$data['id'])->update($authgroup);
         
        $res=db('admin')->where('id',$data['id'])->update($datas);
        
    }
    public function deladmin($id){
      if($this::destroy($id)){
          return 1;
      }else{
          return 2;
      }
    }



    public function login($data){
      $admin=Admin::getByName($data['name']);

      if($admin){
          if($admin['password'] == md5($data['password'])){
            session('id',$admin['id']);
            session('name',$admin['name']);
            return  1;//登录信息正确的情况
          }else{
            return 2;//登录密码错误的情况
          }

      }else{
        return false;//用户名不存在情况
      }
    }
}
